package com.share.finance.collection.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.share.common.common.Page;
import com.share.common.utils.DateUtil;
import com.share.common.utils.DingDingUtil;
import com.share.common.utils.RandomUtil;
import com.share.finance.collection.core.mapper.OverdueInfoMapper;
import com.share.finance.collection.core.mapper.RepaymentPlanMapper;
import com.share.finance.collection.core.model.db.NoticeLog;
import com.share.finance.collection.core.model.db.OverdueInfo;
import com.share.finance.collection.core.model.db.RepaymentPlan;
import com.share.finance.collection.core.model.vo.CallPhoneVo;
import com.share.finance.collection.core.model.vo.LoanCasePageReq;
import com.share.finance.collection.core.service.INoticeLogService;
import com.share.finance.collection.core.service.IOverdueInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 逾期表  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-09-01
 */
@Slf4j
@Service
public class OverdueInfoServiceImpl extends ServiceImpl<OverdueInfoMapper, OverdueInfo> implements IOverdueInfoService {
    @Resource
    private OverdueInfoMapper overdueInfoMapper;

    @Resource
    private RepaymentPlanMapper repaymentPlanMapper;

    @Autowired
    private INoticeLogService noticeLogService;

    @Override
    public int pullOverdueData(Long id) {
        int reCount = 0;
        Long lastId = id;
        Date now = new Date();
        List<RepaymentPlan> list = null;
        do {
            //赛选还款计划
            LambdaQueryWrapper<RepaymentPlan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.lt(RepaymentPlan::getOverdueTime, now);///已经逾期了
            queryWrapper.last("limit 100");
            queryWrapper.orderByDesc(RepaymentPlan::getId);
            if (lastId != null) {
                queryWrapper.lt(RepaymentPlan::getId, lastId);
            }
            list = repaymentPlanMapper.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(list)) {
                //筛选预期记录
                Map<Long, OverdueInfo> overdueInfoMap = new HashMap();
                LambdaQueryWrapper<OverdueInfo> overdueInfoWrapper = new LambdaQueryWrapper<>();
                overdueInfoWrapper.in(OverdueInfo::getPlanId, list.stream().map(p -> p.getId()).collect(Collectors.toList()));//赛选出预期的
                List<OverdueInfo> overdueInfos = overdueInfoMapper.selectList(overdueInfoWrapper);
                if (!CollectionUtils.isEmpty(overdueInfos)) {
                    overdueInfoMap = overdueInfos.stream().collect(Collectors.toMap(OverdueInfo::getPlanId, Function.identity(), (k, v) -> k));
                }

                List<OverdueInfo> insertList = new LinkedList<>();
                List<OverdueInfo> updateList = new LinkedList<>();
                for (RepaymentPlan plan : list) {
                    lastId = plan.getId();
                    OverdueInfo overdueInfo = overdueInfoMap.get(plan.getId());
                    try {
                        OverdueInfo overdue = new OverdueInfo();
                        if (overdueInfo == null) {//新增记录
                            overdue.setBankCard(plan.getBankCard());
                            overdue.setName(plan.getName());
                            overdue.setDueBillNo(plan.getDueBillNo());
                            overdue.setProductCode(plan.getProductCode());
                            overdue.setIdCard(plan.getIdCard());
                            overdue.setSessionId(plan.getSessionId());
                            overdue.setCreateTime(new Date());
                            overdue.setRemainingAmount(plan.getRemainingAmount());
                            overdue.setOverdueInterest(plan.getOverdueInterest());
                            overdue.setRepayInterest(plan.getRepayInterest());
                            overdue.setRepayPrincipal(plan.getRepayPrincipal());
                            overdue.setTerm(plan.getTerm());
                            overdue.setRepayTime(plan.getRepayTime());
                            overdue.setPhoneNo(plan.getPhoneNo());
                            overdue.setUserId(plan.getUserId());
                            overdue.setContactNum(0);//默认是0
                            overdue.setPlanId(plan.getId());
                            overdue.setOverdueTime(plan.getOverdueTime());
                            overdue.setOverdueDay(plan.getOverdueDay());
                            overdue.setRepayTotal(plan.getRepayTotal());

                            //直接分案了
                            overdue.setOperatorId(RandomUtil.rangMinMax(1, 9) + "");
                            insertList.add(overdue);
                        } else {//更新数据
                            overdue.setId(overdue.getId());
                            overdue.setRepayTime(plan.getPayTime());
                            overdue.setOverdueDay(plan.getOverdueDay());
                            overdue.setOverdueInterest(plan.getOverdueInterest());
                            overdue.setRepayTotal(plan.getRepayTotal());
                            updateList.add(overdue);
                        }

                        if (!CollectionUtils.isEmpty(insertList)) {
                            this.saveBatch(insertList);
                        }

                        if (!CollectionUtils.isEmpty(updateList)) {
                            this.saveBatch(updateList);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } while (!CollectionUtils.isEmpty(list));
        return reCount;
    }

    //执行打电话
    @Override
    public Integer callPhone(CallPhoneVo req) {
        int re = 0;
        OverdueInfo overdueInfo = overdueInfoMapper.selectById(req.getOverdueInfoId());
        if (overdueInfo != null) {
            Integer overdueDay = overdueInfo.getOverdueDay();
            String title = null;
            String content = null;
            Integer msgType = null;
            if (overdueDay < 3) {
                msgType = 1;
                title = "逾期通知";
                content = String.format("尊敬的用户%s你好,你已经逾期了%d天,请速度还款,date=%s", overdueInfo.getName(), overdueInfo.getOverdueDay(), DateUtil.getDate());
            } else {
                msgType = 2;
                title = "逾期征信上传通知";
                content = String.format("尊敬的用户%s你好,你已经逾期了%d天,请速度还款,否则上传到人行征信,date=%s", overdueInfo.getName(), overdueInfo.getOverdueDay(), DateUtil.getDate());
            }
            log.info("开始发送消息title={},content={}", title, content);
            int status = DingDingUtil.sendMdMsg(title, content);
            if (status > 0) {
                NoticeLog notice = new NoticeLog();
                notice.setType(msgType);
                notice.setStatus(status);
                notice.setRemark(req.getRemark());
                notice.setMessage(content);
                notice.setName(overdueInfo.getName());
                notice.setPhoneNo(overdueInfo.getPhoneNo());
                notice.setIdCard(overdueInfo.getIdCard());
                notice.setOverdueInfoId(overdueInfo.getId());
                notice.setPlanId(overdueInfo.getPlanId());
                notice.setOperatorId(overdueInfo.getOperatorId());
                notice.setCreateTime(new Date());
                boolean save = noticeLogService.save(notice);

                OverdueInfo overdueInfo2 = new OverdueInfo();
                overdueInfo2.setId(overdueInfo.getId());
                overdueInfo2.setContactNum(overdueInfo.getContactNum() + 1);
                int i = overdueInfoMapper.updateById(overdueInfo2);
                re = 1;
            }
        }
        return re;
    }

    @Override
    public Page<OverdueInfo> pageList(LoanCasePageReq req) {
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        LambdaQueryWrapper<OverdueInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(req.getSessionId())) {
            queryWrapper.like(OverdueInfo::getSessionId, req.getSessionId());
        }
        if (StringUtils.isNotBlank(req.getUserId())) {
            queryWrapper.like(OverdueInfo::getUserId, req.getUserId());
        }
        if (StringUtils.isNotBlank(req.getProductCode())) {
            queryWrapper.like(OverdueInfo::getProductCode, req.getProductCode());
        }

        queryWrapper.orderByDesc(OverdueInfo::getId);
        List<OverdueInfo> list = overdueInfoMapper.selectList(queryWrapper);
        return new Page<>(list, new PageInfo<>(list).getTotal(), req);
    }
}
